﻿// $Id: Program.cs 14 2008-08-21 21:31:25Z jkingry $

namespace Mithril.Server
{
    using System;
    using System.Collections.Specialized;
    using System.Windows.Forms;

    class Program
    {
        static void Main(string[] args)
        {
            NameValueCollection values = GetClickOnceArguments();
            if (values != null)
            {
                Properties.Settings.Default.AccountKey = values["account"];
                Properties.Settings.Default.ServiceBaseAddress = values["hostpath"] + "/service/";
                Properties.Settings.Default.Save();
            }

            Application.Run(new ControlForm());
        }

        private static NameValueCollection GetClickOnceArguments()
        {
            if (AppDomain.CurrentDomain.SetupInformation.ActivationArguments != null &&
                AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData != null)
            {
                string url = AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData[0];
                Uri activationUri = new Uri(url);

                int questionMark = url.IndexOf('?');
                string query = url.Substring(questionMark + 1);
                NameValueCollection values = new NameValueCollection();

                values["hostpath"] = url.Replace(activationUri.PathAndQuery, "");

                foreach(string value in query.Split('&'))
                {
                    int equalsPos = value.IndexOf('=');
                    if (equalsPos >= 0)
                    {
                        values.Add(
                            Uri.UnescapeDataString(value.Substring(0, equalsPos)), 
                            Uri.UnescapeDataString(value.Substring(equalsPos + 1))
                            );
                    }
                    else
                    {
                        values.Add(
                            Uri.UnescapeDataString(value),
                            String.Empty);
                    }
                }
                return values;
            }

            return null;
        }
    }
}
